package com.example.demo.config;

import com.example.demo.service.UserDutailsServicelmpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.crypto.password.NoOpPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.web.bind.annotation.CrossOrigin;

@Configuration
@EnableWebSecurity
@CrossOrigin
public class SecurityConfig  extends WebSecurityConfigurerAdapter {
    @Autowired
   private UserDutailsServicelmpl userDutailsServicelmpl;
    @Override
    protected  void  configure(HttpSecurity http) throws Exception{
        http.authorizeRequests()
                .antMatchers("/").permitAll()
                .antMatchers("/login").permitAll()
                .antMatchers("/register").permitAll()
                .antMatchers("/toregister").permitAll()
                .antMatchers("/tologin").permitAll()
                .antMatchers("/update").permitAll()
                .antMatchers("/insert").hasAnyAuthority("admin")
                .antMatchers("/toinsert").hasAnyAuthority("admin")
                .antMatchers("/toupdate").hasAnyAuthority("admin")
                .antMatchers("/delete").hasAnyAuthority("admin")
                .anyRequest().authenticated();
        http.csrf().disable();
        http.formLogin()
                .loginPage("/login").permitAll()
                .usernameParameter("username").passwordParameter("password")
                .defaultSuccessUrl("/")
                .failureUrl("/error");
        http.rememberMe().rememberMeParameter("rememberme");
        http.logout().logoutSuccessUrl("/");

    }
    @Bean
    public PasswordEncoder noOpPasswordEncoder(){
        return NoOpPasswordEncoder.getInstance();
    }
    @Override
    protected  void configure(AuthenticationManagerBuilder auth) throws Exception{
        auth.userDetailsService(userDutailsServicelmpl).passwordEncoder(noOpPasswordEncoder());
    }

}
